package com.dymedia.aibo.mvp.ui.widget;

import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dymedia.aibo.R;
import com.dymedia.aibo.app.MainApp;
import com.dymedia.aibo.mvp.model.Entity.Channel;
import com.dymedia.aibo.mvp.model.Entity.Group;
import com.dymedia.aibo.mvp.ui.adapter.ChannelAdapter;
import com.dymedia.aibo.mvp.ui.adapter.GroupAdapter;
import com.dymedia.aibo.mvp.ui.holder.GroupHolder;

import java.util.ArrayList;
import java.util.List;

import me.jessyan.art.mvp.Message;
import me.jessyan.art.utils.ArtUtils;
import me.jessyan.art.utils.DataHelper;
import timber.log.Timber;

import static com.dymedia.aibo.mvp.presenter.ChannelPresenter.MSG_ACTION_LIVE_MENU_HIDE;
import static com.dymedia.aibo.mvp.presenter.ChannelPresenter.MSG_ACTION_LIVE_PLAY;

public class TvMenuView extends LinearLayout {
    LinearLayoutManager mLayoutManagerChannel;
    LinearLayoutManager mLayoutManagerGroup;

    RecyclerView recyclerViewChannel;
    RecyclerView recyclerViewGroup;
    ChannelAdapter mAdapterChannel;
    GroupAdapter mAdapterGroup;

    Handler mVisHandler = new Handler();
    Handler mHandler = new Handler();
    Message mCallbackMessage = null;

    List<Group> mDatas;
    boolean mShowGroup = true;

    public TvMenuView(Context context) {
        super(context);
        init();
    }

    public TvMenuView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void setCallback(Message callbackMessage) {
        mCallbackMessage = callbackMessage;
    }

    public void jump(int groupIndex, int channelIndex) {
        DataHelper.setIntergerSF(getContext(), "lastGroup", groupIndex);
        DataHelper.setIntergerSF(getContext(), "lastChannel", channelIndex);
    }

    public void setShowGroup(boolean show) {
        mShowGroup = show;
        if (!mShowGroup) {
            recyclerViewGroup.setVisibility(View.GONE);
        }
    }

    public void setDatas(List<Group> groups) {
        mAdapterGroup.getInfos().clear();
        mAdapterGroup.getInfos().addAll(groups);
        mDatas = groups;
    }

    public void notifyDataSetChanged() {
        mAdapterGroup.notifyDataSetChanged();
        if (isShow()) {
            if (mShowGroup) {
                recyclerViewGroup.requestFocus();
            } else {
                int position = 0;
                DataHelper.setIntergerSF(getContext(), "lastGroup", position);
                mAdapterChannel.setInfos(mDatas.get(position).channels);
                mAdapterChannel.notifyDataSetChanged();
            }
            autoHide();//第一次
        }
    }

    public boolean isShow() {
        return getVisibility() == View.VISIBLE;
    }

    public void show() {
        Timber.d("show");
        ((View)getParent()).setVisibility(View.VISIBLE);
        setVisibility(View.VISIBLE);
        recyclerViewGroup.requestFocus();

//        mHandler.post(new Runnable() {
//            @Override
//            public void run() {
//                int index = groupIndex;
//                View v3 = mLayoutManagerGroup.findViewByPosition(index);
//                if (v3 != null) {
//                    Timber.d("show, focus: "+index);
//                    if (!(index >= mLayoutManagerGroup.findFirstCompletelyVisibleItemPosition() && index < mLayoutManagerGroup.findLastCompletelyVisibleItemPosition())) {
//                        mLayoutManagerGroup.scrollToPosition(index);
//                        mLayoutManagerGroup.scrollToPositionWithOffset(index, 0);
//                    }
//                    recyclerViewGroup.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
//                    v3.requestFocus();
//                } else {
//                    mHandler.postDelayed(this, 50);
//                }
//            }
//        });
    }

    private void autoHide() {
        if (isShow()) {
            mVisHandler.removeCallbacksAndMessages(null);
            mVisHandler.postDelayed(() -> {
                hide();
                mCallbackMessage.what = MSG_ACTION_LIVE_MENU_HIDE;
                mCallbackMessage.handleMessageToTargetUnrecycle();
            }, 6000);
        }
    }

    //焦点处理注意：
    // 父窗口android:focusable="true"，此时recycleView不会自动获取
    // 父窗口从隐藏到显示，recycleView会自动获取一次焦点
    public void hide() {
        isChannelFocus = false;
        setVisibility(View.GONE);
        recyclerViewChannel.setTag(null);
        //recyclerViewGroup.setTag(null);
        mVisHandler.removeCallbacksAndMessages(null);
        recyclerViewGroup.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
    }

    boolean isChannelFocus = false;
    int groupIndex = 0;
    int findFirstVisibleItemPosition = 0;
    int visibleItemPosition = 0;
    private void playAction(int groupIndex, int itemIndex) {
        Timber.d(String.format("playAction, groupIndex=%d, itemIndex=%d", groupIndex, itemIndex));
        if (groupIndex >= 0 && groupIndex < mDatas.size() && itemIndex >= 0 && itemIndex < mDatas.get(groupIndex).channels.size()) {
            Channel c = mDatas.get(groupIndex).channels.get(itemIndex);
            if (c != null && mCallbackMessage != null) {
                DataHelper.setIntergerSF(getContext(), "lastGroup", groupIndex);
                DataHelper.setIntergerSF(getContext(), "lastChannel", itemIndex);

                mCallbackMessage.obj = c;
                mCallbackMessage.what = MSG_ACTION_LIVE_PLAY;
                mCallbackMessage.handleMessageToTargetUnrecycle();
            }
        }
    }
    View curView = null;
    private void init() {
        View rootView = LayoutInflater.from(getContext()).inflate(R.layout.widget_tvmenu, this);
        recyclerViewChannel = rootView.findViewById(R.id.recyclerViewChannel);
        recyclerViewGroup = rootView.findViewById(R.id.recyclerViewGroup);

        recyclerViewChannel.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                autoHide();
            }
        });
        recyclerViewGroup.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                autoHide();
            }
        });

        this.mAdapterChannel = new ChannelAdapter(new ArrayList<>());
        this.mAdapterGroup = new GroupAdapter(new ArrayList<>());

        mLayoutManagerChannel = new LinearLayoutManager(getContext());
        ArtUtils.configRecyclerView(recyclerViewChannel, mLayoutManagerChannel);
        recyclerViewChannel.setAdapter(mAdapterChannel);
        mAdapterChannel.setFocusChangeListener((position, hasFocus) -> {
            Timber.d("mAdapter, onFocusChange, currentPosition: " + position + ", hasFocus: " + hasFocus);
            View v = mLayoutManagerChannel.findViewByPosition(position);
            if (hasFocus) {
                autoHide();
                //v.requestFocus();
                View v2 = (View) recyclerViewChannel.getTag();
                recyclerViewChannel.setTag(v);
                if (v2 != null) {
                    //DataHelper.setIntergerSF(getContext(), "lastChannel", position);
                }
                View groupView = (View) recyclerViewGroup.getTag();
                if (groupView != null) {
                    //groupView.setBackgroundColor(Color.RED);
                    //GroupHolder vh = (GroupHolder)recyclerViewGroup.findViewHolderForAdapterPosition((int)groupView.getTag());
                    //vh.holdFocus();
                }
            }
        });
        mAdapterChannel.setKeyChangeListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_DPAD_DOWN:
//                        View focusItem = (View)recyclerViewGroup.getTag();
//                        if (focusItem != null){//禁止下键跳转到频道列表
//                            Integer currentPosition = (Integer)focusItem.getTag();
//                            if (currentPosition >= mAdapter.getInfos().size()-1){
//                                return true;
//                            }
//                        }
                        mVisHandler.removeCallbacksAndMessages(null);
                        isChannelFocus = true;
                        break;
                    case KeyEvent.KEYCODE_DPAD_UP:
                        mVisHandler.removeCallbacksAndMessages(null);
                        isChannelFocus = true;
                        if ((int) v.getTag() <= 0){
                            return true;
                        }
//                        v = FocusFinder.getInstance().findNextFocus(TvMenuView.this, (View)recyclerViewGroup.getTag(), FOCUS_UP);
                        break;
                    case KeyEvent.KEYCODE_DPAD_LEFT:
                        mVisHandler.removeCallbacksAndMessages(null);
                        isChannelFocus = false;
                        View v2 = (View) recyclerViewGroup.getTag();//分组焦点
                        if (v2 != null)
                            v2.requestFocus();
                        return true;
                    case KeyEvent.KEYCODE_DPAD_CENTER:
                    case KeyEvent.KEYCODE_ENTER:
                        View v3 = (View) recyclerViewGroup.getTag();
                        View v4 = (View) recyclerViewChannel.getTag();
                        if (v3 != null && v4 != null) {
                            playAction((int) v3.getTag(), (int) v4.getTag());
                        }
                        return true;
                    default:
                        //mVisHandler.removeCallbacksAndMessages(null);
                        break;
                }
            }
            return false;
        });
        mAdapterChannel.setClickedListener(v -> {
            if (mShowGroup) {
                View v3 = (View) recyclerViewGroup.getTag();
                View v4 = v;
                if (v3 != null && v4 != null) {
                    DataHelper.setIntergerSF(getContext(), "lastGroup", (Integer) v3.getTag());
                    playAction((int) v3.getTag(), (int) v4.getTag());
                }
            } else if (v != null){
                playAction(0, (int) v.getTag());
            }
        });

        mLayoutManagerGroup = new LinearLayoutManager(getContext());
        ArtUtils.configRecyclerView(recyclerViewGroup, mLayoutManagerGroup);
        recyclerViewGroup.setAdapter(mAdapterGroup);
        recyclerViewGroup.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    recyclerViewGroup.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
                    View v5 = mLayoutManagerGroup.findViewByPosition(groupIndex);
                    if(v5!=null){
                        Timber.d("aaaaaaaaaa"+(int)v5.getTag());
                        v5.requestFocus();
                    }
                }
            }
        });
        mAdapterGroup.setFocusChangeListener((position, hasFocus) -> {
            View v = mLayoutManagerGroup.findViewByPosition(position);
            View v2 = (View) recyclerViewGroup.getTag();
            Timber.d("mAdapterGroup, onFocusChange, currentPosition: " + position + ", hasFocus: " + hasFocus);
            if (hasFocus) {
                autoHide();
                if (mLayoutManagerGroup.findFirstVisibleItemPosition() + visibleItemPosition == groupIndex) {
                    View v4 = recyclerViewGroup.getChildAt(groupIndex-mLayoutManagerGroup.findFirstVisibleItemPosition());
                    if (v4 != null && v4.findViewById(R.id.tv_name) != null) {
                        ((TextView) v4.findViewById(R.id.tv_name)).setTextColor(getResources().getColor(R.color.listItemTextColor));
                    }
                }
                if (v != null && v.findViewById(R.id.tv_name) != null) {
                    ((TextView) v.findViewById(R.id.tv_name)).setTextColor(getResources().getColor(R.color.listItemTextFocusColor));
                }

                if (isChannelFocus) {//解决频道快速上翻会自动跳到分组的问题
                    View v8 = (View) recyclerViewChannel.getTag();
                    if (v8 != null) v8.requestFocus();
                    return;
                }
                groupIndex = position;
                findFirstVisibleItemPosition = mLayoutManagerGroup.findFirstVisibleItemPosition();
                visibleItemPosition = groupIndex-findFirstVisibleItemPosition;
                recyclerViewGroup.setTag(v);
                curView = v;
                if (position >= 0 && position < mDatas.size()) {
                    mAdapterChannel.setInfos(mDatas.get(position).channels);
                    mAdapterChannel.notifyDataSetChanged();
                }
            } else {

//                if (v2 != null) { // 颜色
//                    ((TextView) v2.findViewById(R.id.tv_name)).setTextColor(getResources().getColor(R.color.listItemTextColor));
//                }
            }
        });
        mAdapterGroup.setKeyChangeListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_DPAD_UP:
                        if ((int) v.getTag() <= 0){
                            return true;
                        }
                        break;
                    case KeyEvent.KEYCODE_DPAD_DOWN:
                        View focusItem = (View) recyclerViewGroup.getTag();
                        if (focusItem != null) {//禁止下键跳转到频道列表
                            Integer position = (Integer) focusItem.getTag();
                            if (position >= mAdapterGroup.getInfos().size() - 1) {
                                return true;
                            }
                        }
                        //View v = FocusFinder.getInstance().findNextFocus(TvMenuView.this, (View)recyclerViewGroup.getTag(), FOCUS_RIGHT);
                        break;
                }
            }
            return false;
        });

//        recyclerViewVideo.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                if (mLayoutManager.getChildCount() > 0 && visibleCount == 0) {
//                    visibleCount = mLayoutManager.findLastVisibleItemPosition() - mLayoutManager.findFirstVisibleItemPosition();
//                    mPresenter.getLastChannel(Message.obtain(ChannelActivity.this, new Object[]{}));
//                    Timber.d("onGlobalLayout: " + visibleCount);
//                }
//            }
//        });

//        mVisHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                View v = findFocus();
//                if (v != null)
//                    Timber.d("aaaaa:"+v.toString());
//                mVisHandler.postDelayed(this, 3000);
//            }
//        }, 4000);
    }
}
